package platform.user.auth.token.store;

import org.springframework.beans.factory.annotation.Autowired;
import platform.user.auth.token.SessionToken;

import java.util.UUID;

/**
 * Token 业务实现
 *
 * @author roamer
 * @version V1.0
 * @date 2019-03-11 17:24
 */
public class PersistentTokenStore implements TokenStore {

    @Autowired
    private TokenRepository tokenRepository;

    @Override
    public boolean isValidToken(String tokenValue) {
        SessionToken token = null;
        try {
            token = tokenRepository.queryByValue(UUID.fromString(tokenValue));
        } catch (Exception e) {
            return false;
        }

        if ((token == null)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void addToken(SessionToken token) {
        if (token != null) {
            tokenRepository.save(token);
        }
    }

    @Override
    public void removeToken(SessionToken token) {
        if (token != null) {
            tokenRepository.delete(token);
        }
    }

    @Override
    public SessionToken getTokenByValue(String tokenValue) {
        try {
            return tokenRepository.queryByValue(UUID.fromString(tokenValue));
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void updateToken(SessionToken token) {
        if (token != null) {
            tokenRepository.save(token);
        }
    }
}
